import shutil
import os
import unittest


def base_wrap(basefunc):
    def wrap_1(func):
        def wrap(*args, **kargs):
            basefunc(*args, **kargs)
            func(*args, **kargs)

        return wrap

    return wrap_1


class ShutilTest(unittest.TestCase):
    def setUp(self):
        with open('hello.txt', 'w') as f:
            f.write('hello world')
        f.close()

    def tearDown(self):
        p = os.path.dirname(os.path.abspath(__file__))
        for root, dirs, files in os.walk(p):
            for dir_item in dirs:
                shutil.rmtree(dir_item)

    def testcopyfile2dir(self):
        tmp_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp')
        # 如果tmp不存在，tmp将会被认定为一个文件，而不是一个文件夹来处理
        if not os.path.exists(tmp_dir):
            os.mkdir(tmp_dir)
        shutil.copy('hello.txt', tmp_dir)
        if os.path.exists(os.path.join(tmp_dir, 'hello.txt')):
            self.assertTrue('copy file success')
        else:
            self.assertFalse('copy file failed')

    def testcopyfile2file(self):
        # 直接复制到一个文件中
        tmp_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'hello1.txt')
        shutil.copy('hello.txt', tmp_file)
        if os.path.exists(tmp_file):
            self.assertTrue('copy file success')
        else:
            self.assertFalse('copy file failed')

    @base_wrap(testcopyfile2dir)
    def testcopytree(self):
        """将src目录下的所有的文件已经子文件夹复制到dest目录下"""
        tmp_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp')
        tmp_dir_2 = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp2')
        shutil.copytree(tmp_dir, tmp_dir_2)
        if os.path.exists(os.path.join(tmp_dir_2, 'hello.txt')):
            self.assertTrue('success')
        else:
            self.assertFalse('failed')

    @base_wrap(testcopyfile2dir)
    def testmove2dir(self):
        tmp_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp')
        tmp_dir_2 = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp2')
        if not os.path.exists(tmp_dir_2):
            os.mkdir(tmp_dir_2)
        shutil.move(tmp_dir, tmp_dir_2)
        if os.path.exists(os.path.join(tmp_dir_2, 'tmp')):
            self.assertTrue('success')
        else:
            self.assertFalse('failed')

    def testmove2file(self):
        shutil.move('hello.txt', 'hello_tmp.txt')
        if os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'hello_tmp.txt')):
            self.assertTrue('success')
        else:
            self.assertFalse('false')

    def testunlink(self):
        os.unlink('hello.txt')
        if os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'hello.txt')):
            self.assertFalse('false')
        else:
            self.assertTrue('success')


if __name__ == "__main__":
    unittest.main()
